import mysql.connector
from mysql.connector import errorcode
from datetime import datetime, timedelta
import random

# 数据库配置信息，请确保与 create_bunnyspell_tables.py 中的配置相同
import os
from dotenv import load_dotenv

load_dotenv()

DB_NAME = os.getenv('DB_NAME')
db_config = {
    'user': os.getenv('DB_USER'),
    'password': os.getenv('DB_PASSWORD'),
    'host': os.getenv('DB_HOST'),
    'database': DB_NAME
}


def insert_game_records():
    try:
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor()

        # 准备插入语句
        insert_query = """
        INSERT INTO game_records
        (game_id, user_id, score, completion_rate, status, completed_at, created_at)
        VALUES (%s, %s, %s, %s, %s, %s, %s)
        """

        # 生成20条记录
        records = []
        end_date = datetime.now()
        start_date = end_date - timedelta(days=3)

        for _ in range(3):
            game_id = 2
            user_id = 1
            score = random.randint(0, 100)
            completion_rate = round(random.uniform(0, 1), 2)
            status = random.choice(['not_started', 'in_progress', 'completed'])
            created_at = start_date + \
                timedelta(seconds=random.randint(0, int((end_date - start_date).total_seconds())))
            completed_at = created_at + timedelta(minutes=random.randint(5, 30))

            records.append(
                (game_id,
                 user_id,
                 score,
                 completion_rate,
                 status,
                 completed_at,
                 created_at))

        # 执行批量插入
        cursor.executemany(insert_query, records)
        conn.commit()

        print(f"Successfully inserted {cursor.rowcount} records into game_records table.")

    except mysql.connector.Error as err:
        print(f"Error: {err}")
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()


if __name__ == "__main__":
    insert_game_records()
